#include <GUI/Widgets/CurtainWidget.hpp>
#include <FL/Fl_PNG_Image.H>
#include <FL/fl_draw.H>
#include <cstdio>

#ifndef RESOURCE_DIR
#define RESOURCE_DIR "."
#endif

Fl_PNG_Image* CurtainWidget::s_img_on = nullptr;
Fl_PNG_Image* CurtainWidget::s_img_off = nullptr;

static void ensure_png_loaded_curtain()
{
    if (!CurtainWidget::s_img_on)
    {
        char path_on[512];
        std::snprintf(path_on, sizeof(path_on), "%s/curtain_on.png", RESOURCE_DIR);
        CurtainWidget::s_img_on = new Fl_PNG_Image(path_on);
        if (CurtainWidget::s_img_on->fail())
        {
            std::fprintf(stderr, "[CurtainWidget] 加载失败: %s\n", path_on);
            delete CurtainWidget::s_img_on;
            CurtainWidget::s_img_on = nullptr;
        }
    }
    if (!CurtainWidget::s_img_off)
    {
        char path_off[512];
        std::snprintf(path_off, sizeof(path_off), "%s/curtain_off.png", RESOURCE_DIR);
        CurtainWidget::s_img_off = new Fl_PNG_Image(path_off);
        if (CurtainWidget::s_img_off->fail())
        {
            std::fprintf(stderr, "[CurtainWidget] 加载失败: %s\n", path_off);
            delete CurtainWidget::s_img_off;
            CurtainWidget::s_img_off = nullptr;
        }
    }
}

CurtainWidget::CurtainWidget(int x, int y, int w, int h, const char* label)
    : Fl_Box(x, y, w, h)
{
    box(FL_NO_BOX); // 去除自身背景
    align(FL_ALIGN_BOTTOM | FL_ALIGN_INSIDE);
    copy_label(label);
    labelsize(12);
    labelfont(FL_COURIER_BOLD);
    labelcolor(FL_BLACK); // 适配白色卡片
    ensure_png_loaded_curtain();
    set_state(false);
}

void CurtainWidget::set_state(bool open)
{
    is_open_ = open;
    Fl_PNG_Image* pic = is_open_ ? s_img_on : s_img_off;

    // 释放之前的拷贝，避免泄漏
    if (image())
    {
        delete image();
        image(nullptr);
    }

    if (pic)
    {
        int target_w = w();
        int target_h = h() - 16; // 预留底部文字
        if (target_h < 8) target_h = h();
        Fl_Image* display_img = pic->copy(target_w, target_h);
        image(display_img);
    }
    else
    {
        // 无资源时不渲染背景
    }
    redraw();
}
